from flask import Blueprint, jsonify
from flask_restful import Api, Resource, reqparse,  marshal

from models.models import *
from utils.models_fields import *
cour_bp = Blueprint("cour",__name__)
api = Api(cour_bp)

class CourseView(Resource):
    def get(self):
        req = reqparse.RequestParser()
        req.add_argument("id")
        args = req.parse_args()
        print("参数id",args['id'])
        try:
            cour_info = Course.query.filter(Course.id == args['id']).first()
            print("查询课程成功",cour_info)

            data = {
                "id":cour_info.id,
                "name":cour_info.name,
                "info":cour_info.info,
                "create_time":cour_info.create_time,
                "start_time":cour_info.start_time,
                "end_time":cour_info.end_time,
                "total":cour_info.total,
                "total_time":cour_info.total_time,
                "photo":cour_info.photo,

                "type":cour_info.type,
                "teacher_num":cour_info.teacher_num,
                "collect_num":cour_info.collect_num,
                "course_num":cour_info.course_num,
                "buy_num":cour_info.buy_num,
                "stu_num":cour_info.stu_num,
                "solo_num":cour_info.solo_num,
                "vip_free":cour_info.vip_free,
            }
            return jsonify({
                "code":200,
                "msg":"查询课程大纲成功",
                "data":data
            })
        except Excerpt as e:
            print("查询课程大纲错误",e)
            return jsonify({
                "code":400,
                "msg":"没有该课程"
            })

api.add_resource(CourseView,"/cours_info")


class CourseAll(Resource):
    def get(self):
        course = Course.query.all()
        if course:
            course = marshal(course,course_fields)
            return course

api.add_resource(CourseAll,'/courseall')

class CourseExcerpt(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id')
        args = parser.parse_args()
        id = args.get('id')
        excerpt = Excerpt.query.filter_by(course_id=id).all()
        if excerpt:
            excerpt = marshal(excerpt,exec_fields)
            return excerpt
api.add_resource(CourseExcerpt,'/courseexce')

